package com.ymwk;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;

import com.ymwk.base64.Base64Utils;
import com.ymwk.file.FileUtils;
import com.ymwk.sm2.SM2Util;
import com.ymwk.sm4.Sm4Utils;

public class DecryptFile {

	/**
	 * 
	 * @param privateKey   私钥
	 * @param file 加密后的文件
	 * @param keyString   加密后的秘钥
	 * return  文件保存地址
	 */
	public static String decrypt(PrivateKey privateKey,File file,String keyString) throws IOException, InvalidCipherTextException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException {
		byte[] keyByte = Base64Utils.decode(keyString);
		FileInputStream fileInputStream = new FileInputStream(file);
		ByteArrayOutputStream output = new ByteArrayOutputStream();
	    byte[] buffer = new byte[4096];
	    int n = 0;
	    while (-1 != (n = fileInputStream.read(buffer))) {
	        output.write(buffer, 0, n);
	    }
	     byte[] byteArray = output.toByteArray();
		//用私钥解密秘钥
		byte[] key = SM2Util.decrypt((BCECPrivateKey)privateKey, keyByte);
		byte[] decryptEcbPadding = Sm4Utils.decrypt_ECB_Padding(key, byteArray);
		String generateFilePath = FileUtils.generateFilePath(file.getParent(),file.getName());
		OutputStream out = new FileOutputStream(generateFilePath);
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decryptEcbPadding);
		byte[] buff = new byte[1024];
        int len = 0;
        while((len=byteArrayInputStream.read(buff))!=-1){
            out.write(buff, 0, len);
        }
        byteArrayInputStream.close();
        out.close();
        return generateFilePath;
	    	
	}
	
	
}
